package com.ydd.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import com.ydd.common.exception.BusinessException;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotBlank;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:解析excel TListener dateList = new TListener();
 * EasyExcel.read(file.getInputStream(), xxx.class, dateList).sheet().doRead();
 * List<xxx> returnList = dateList.getDate();
 * 字段上写注解@ExcelProperty(value = "表头")
 */

@Setter
@Getter
@Slf4j
public class TListener<T> extends AnalysisEventListener<T> {

    private List<T> date = new ArrayList<>();

    @Override
    public void invoke(T model, AnalysisContext context) {
        Class<?> aClass = model.getClass();


        // 获取对象的所有字段
        Field[] fields = aClass.getDeclaredFields();
//         遍历字段进行非空检查
        for (Field field : fields) {
            //如果写了这个注解,会进行参数校验
            NotBlank annotation = field.getAnnotation(NotBlank.class);

            if (annotation != null) {

                // 设置字段可访问
                field.setAccessible(true);
                // 获取字段的值
                Object value = null;
                try {
                    value = field.get(model);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                // 检查字段值是否为空
                if (value == null || value.equals("")) {
                    try {
                        throw new BusinessException((String) annotation.annotationType().getMethod("message").invoke(annotation));
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }

            }
        }
        date.add(model);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {


    }

}
